//
//  BaseUIScrollView.m
//  NovartisPPH
//
//  Created by Sidney on 13-9-26.
//  Copyright (c) 2013年 iSoftstone infomation Technology (Group) Co.,Ltd. All rights reserved.
//

#import "BaseUIScrollView.h"

@interface BaseUIScrollView ()

@property(nonatomic,strong)UIButton * loadMoreBtn;
@property(nonatomic,strong)UIView * refreshView;

@property(nonatomic,assign)BOOL isLoadMore;//下拉加载更多
@property(nonatomic,assign)BOOL isRefreshfirstPage;//上拉刷新

@property(nonatomic,strong)UIImageView * topLogoView;

@property(nonatomic,strong)UILabel * lastUpdateTimeLabel;
@property(nonatomic,strong)UILabel * refreshTipLabel;
@property(nonatomic,strong)UIActivityIndicatorView * refreshindicator;

@property(nonatomic,assign)float curContentOffsetX;
@property(nonatomic,assign)float lastContentOffsetX;
@property(nonatomic,assign)float curContentOffsetY;
@property(nonatomic,assign)float lastContentOffsetY;

@end

@implementation BaseUIScrollView

static int loadMoreViewheight = 60;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
        _curContentOffsetX = 0;
		_curContentOffsetY = 0;

    }
    return self;
}
- (void)addReloadMoreDataBtn
{
    if (!_loadMoreBtn) {
        _loadMoreBtn = [[UIButton alloc] init];
        [_loadMoreBtn setTitle:@"向上滑动加载更多..." forState:UIControlStateNormal];
        [_loadMoreBtn setBackgroundColor:[UIColor clearColor]];
        [_loadMoreBtn setTitleColor:MAIN_BLACK_COLOR forState:UIControlStateNormal];
        [_loadMoreBtn addTarget:self action:@selector(loadMoreBtnPressed) forControlEvents:UIControlEventTouchUpInside];
        
        float height = loadMoreViewheight - 10 * 2;
        float width = CGRectGetWidth(self.frame) - 100;
        float originY = (loadMoreViewheight - height) / 2;
        float originX = (CGRectGetWidth(self.frame) - width) / 2;
        [_loadMoreBtn setFrame:CGRectMake(originX, originY, width, height)];
        
        _topLogoView = [[UIImageView alloc] init];
        _topLogoView.image = [UIImage imageNamed:@"image_top_2_logo"];
        [self addSubview:_topLogoView];
        
    }
    [self refreshLoadMoreBtnFrame];
    [self addSubview:_loadMoreBtn];
    _isLoadMore = YES;
}

- (void)refreshLoadMoreBtnFrame
{
    CGSize tempSize = self.contentSize;
    tempSize.height += loadMoreViewheight;
    self.contentSize = tempSize;
    float height = loadMoreViewheight - 10 * 2;
    float width = CGRectGetWidth(self.frame) - 100;
    float originY = (loadMoreViewheight - height) / 2 ;
    float originX = (CGRectGetWidth(self.frame) - width) / 2;
    [_loadMoreBtn setFrame:CGRectMake(originX, tempSize.height - originY - height, width, height)];
    _topLogoView.frame = CGRectMake((CGRectGetWidth(self.frame) - 143) / 2,CGRectGetMaxY(_loadMoreBtn.frame) + 20, 143, 35);
}

- (void)removeReloadMoreDataBtn
{
    self.contentSize = CGSizeMake(CGRectGetWidth(self.frame), self.contentSize.height - loadMoreViewheight);
    [_loadMoreBtn removeFromSuperview];
    _loadMoreBtn = nil;
    _isLoadMore = NO;
}

- (void)loadMoreBtnPressed
{
    if ([_opetationDelegate respondsToSelector:@selector(getMoreData:)]) {
        [_opetationDelegate getMoreData:self];
    }
}

- (void)refreshLastUpdateDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy-MM-dd HH:mm"];
    _lastUpdateTimeLabel.text = [NSString stringWithFormat:@"最后更新:%@",[formatter stringFromDate:[NSDate date]]];
    [[NSUserDefaults standardUserDefaults] setObject:_lastUpdateTimeLabel.text forKey:@"LastRefreshTime"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [_refreshindicator stopAnimating];
}


- (void)addRefreshFirstPageView
{
    _isRefreshfirstPage = YES;
    if (!_refreshView) {
        float height = 70;
        float width = CGRectGetWidth(self.frame) - 30;
        float originY = -75;
        float originX = (CGRectGetWidth(self.frame) - width) / 2;
        
        UIImageView * topLogo = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(self.frame) - 150) / 2,-150, 150, 70)];
        topLogo.image = [UIImage imageNamed:@"image_top_1_logo"];
        [self addSubview:topLogo];
        
        _refreshView = [[UIView alloc] initWithFrame:CGRectMake(originX, originY, width, height)];
        _refreshView.backgroundColor = [UIColor clearColor];
        
        _refreshTipLabel = [[UILabel alloc] initWithFrame:CGRectMake((width - 200) / 2, 10, 200, 30)];
        _refreshTipLabel.textColor = MAIN_BLACK_COLOR;
        _refreshTipLabel.backgroundColor = [UIColor clearColor];
        _refreshTipLabel.font = [UIFont systemFontOfSize:18];
        _refreshTipLabel.text = @"下拉可以刷新";
        _refreshTipLabel.textAlignment = NSTextAlignmentCenter;
        [_refreshView addSubview:_refreshTipLabel];
        
        
        _lastUpdateTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake((width - 200) / 2, 30, 230, 40)];
        _lastUpdateTimeLabel.backgroundColor = [UIColor clearColor];
        _lastUpdateTimeLabel.textColor = MAIN_BLACK_COLOR;
        _lastUpdateTimeLabel.font = [UIFont systemFontOfSize:18];
        NSString * time = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastRefreshTime"];
        
        if (!time) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yy-MM-dd HH:mm"];
            time = [NSString stringWithFormat:@"最后更新:%@",[formatter stringFromDate:[NSDate date]]];
        }
        
        _lastUpdateTimeLabel.text = time;
        _lastUpdateTimeLabel.textAlignment = NSTextAlignmentCenter;
        [_refreshView addSubview:_lastUpdateTimeLabel];
        
        _refreshindicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        _refreshindicator.frame = CGRectMake(CGRectGetMinX(_lastUpdateTimeLabel.frame) - 35 , 27, 25, 25);
        [_refreshindicator setHidesWhenStopped:YES];
        [_refreshView addSubview:_refreshindicator];
        
    }
    [self addSubview:_refreshView];
}

- (void)startRefreshFirstPage
{
    [UIView animateWithDuration:0.3f
                     animations:^{
//                         [self setContentOffset:CGPointMake(0, 80)];
                         [self setContentInset:UIEdgeInsetsMake(80, 0, 0, 0)];
                         [_refreshindicator startAnimating];
                         _refreshTipLabel.text = @"加载中...";
                     }];
    if ([_opetationDelegate respondsToSelector:@selector(refreshFirstPage:)]) {
        [_opetationDelegate refreshFirstPage:self];
    }
}

- (void)stopRefreshFirstPage
{
    [UIView animateWithDuration:0.3f
                     animations:^{
                         [self setContentOffset:CGPointZero];
                         [self setContentInset:UIEdgeInsetsZero];
                         [self refreshLastUpdateDate];
                         _refreshTipLabel.text = @"下拉可以刷新";
                     } ];
}


- (void)removeRefreshFirstPageView
{
    [self stopRefreshFirstPage];
    _isRefreshfirstPage = NO;
    [_refreshView removeFromSuperview];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    _lastContentOffsetX = _curContentOffsetX;
	_lastContentOffsetY = _curContentOffsetY;
	_curContentOffsetX = scrollView.contentOffset.x;
	_curContentOffsetY = scrollView.contentOffset.y;
	
    if (_curContentOffsetX > _lastContentOffsetX || _curContentOffsetY > _lastContentOffsetY) {
		_scrollDir = DOWN_RIGHT;
	}else if (_curContentOffsetX < _lastContentOffsetX || _curContentOffsetY < _lastContentOffsetY){
		_scrollDir = UP_LEFT;
	}
    
    if (_isRefreshfirstPage) {
        int offset = scrollView.contentOffset.y;
        if (![_refreshTipLabel.text isEqualToString:@"加载中..."]) {
            if (offset < -80) {
                _refreshTipLabel.text = @"松开刷新";
            }else{
                _refreshTipLabel.text = @"下拉可以刷新";
            }
        }
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (decelerate) {
        float hight = scrollView.contentSize.height;
        float offsetY = (scrollView.contentOffset.y + CGRectGetHeight(self.frame));
        
        if (_isLoadMore) {
            if ((offsetY - hight > 60)) {
                [self loadMoreBtnPressed];
            }
        }
//        NSLog(@"%f",scrollView.contentOffset.y);
        if(_isRefreshfirstPage)
        {
            if (scrollView.contentOffset.y < -80){
                [self startRefreshFirstPage];
            }
        }
    }else{
        //NSLog(@"NO");
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
